<template>
  <div class="home-container">
    <div class="header">
      <h1>音乐识别</h1>
      <p>点击按钮开始识别当前播放的音乐</p>
    </div>

    <div class="content">
      <div class="music-icon" :class="{ recording: isRecording }">
        <svg width="64" height="64" viewBox="0 0 24 24" fill="#333">
          <path
            d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"
          />
        </svg>
      </div>

      <button class="record-btn" @click="startRecognition" :disabled="isRecording">
        {{ isRecording ? "识别中..." : "开始识别" }}
      </button>

      <div v-if="loading" class="loading">
        <svg width="32" height="32" viewBox="0 0 24 24" fill="#007aff" class="spinner">
          <path
            d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"
          />
        </svg>
        <p>正在分析...</p>
      </div>
    </div>

    <div class="tips">
      <p>识别说明：</p>
      <ul>
        <li>请确保环境安静，音乐清晰</li>
        <li>识别过程可能需要几秒钟</li>
        <li>支持主流音乐识别</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isRecording: false,
      loading: false,
      audioContext: null,
      mediaRecorder: null,
      audioChunks: [],
    };
  },
  methods: {
    async startRecognition() {
      try {
        // 开始录音状态
        this.isRecording = true;
        this.audioChunks = [];

        // 请求麦克风权限
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

        // 创建录音实例（使用mp3格式以获得更好的兼容性）
        const options = {
          mimeType: "audio/webm;codecs=opus", // 使用opus编码以获得更好的压缩率
        };

        // 如果浏览器不支持opus编码，回退到默认格式
        if (!MediaRecorder.isTypeSupported(options.mimeType)) {
          options.mimeType = "audio/webm";
        }

        this.mediaRecorder = new MediaRecorder(stream, options);

        this.mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            this.audioChunks.push(event.data);
          }
        };

        this.mediaRecorder.onstop = async () => {
          this.isRecording = false;
          this.loading = true;

          try {
            // 创建音频Blob
            const audioBlob = new Blob(this.audioChunks, { type: options.mimeType });

            // AudD API 配置
            const AUD_API_TOKEN = "test"; // 免费测试token，实际使用时建议更换为正式token
            const formData = new FormData();
            formData.append("file", audioBlob, "audio.webm");
            formData.append("api_token", AUD_API_TOKEN);
            formData.append("return", "apple_music,spotify,deezer");

            // 调用AudD音乐识别API
            const response = await fetch("https://api.audd.io/", {
              method: "POST",
              body: formData,
            });

            const data = await response.json();

            if (data.result) {
              // 构建音乐信息对象
              const musicInfo = {
                title: data.result.title || "未知标题",
                artist: data.result.artist || "未知艺术家",
                album: data.result.album || "未知专辑",
                composer: data.result.composer || "未知作曲",
                lyricist: data.result.lyricist || "未知作词",
                releaseDate: data.result.release_date || "未知发行日期",
                duration: this.formatDuration(data.result.duration_sec) || "未知时长",
                genre: data.result.genre || "未知流派",
                cover:
                  data.result.spotify?.album?.images?.[0]?.url ||
                  data.result.deezer?.album?.cover_big ||
                  data.result.apple_music?.artwork?.url ||
                  "",
              };

              this.loading = false;
              // 跳转到详情页
              this.$router.push({
                path: "/detail",
                query: { musicInfo: JSON.stringify(musicInfo) },
              });
            } else {
              this.loading = false;
              alert("未能识别出音乐，请尝试在更安静的环境下重新录制");
              console.log("识别失败原因:", data.error);
            }
          } catch (apiError) {
            console.error("API调用失败:", apiError);
            this.loading = false;
            alert("识别服务暂时不可用，请稍后重试");
          } finally {
            // 停止所有音频轨道
            stream.getTracks().forEach((track) => track.stop());
          }
        };

        // 开始录音，持续5秒
        this.mediaRecorder.start();
        setTimeout(() => {
          if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
            this.mediaRecorder.stop();
          }
        }, 5000);
      } catch (error) {
        console.error("录音失败:", error);
        this.isRecording = false;
        alert("录音权限被拒绝或录音设备不可用");
      }
    },

    // 格式化时长
    formatDuration(seconds) {
      if (!seconds || isNaN(seconds)) return null;
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins}:${secs.toString().padStart(2, "0")}`;
    },
  },
};
</script>

<style scoped>
.home-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f8f8f8;
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.header p {
  font-size: 16px;
  color: #666;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.music-icon {
  margin-bottom: 30px;
  transition: all 0.3s ease;
}

.music-icon.recording {
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.record-btn {
  width: 200px;
  height: 60px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 30px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.record-btn:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
}

.record-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  transform: none;
}

.loading {
  position: absolute;
  bottom: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading p {
  margin-top: 10px;
  color: #007aff;
}

.spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.tips {
  margin-top: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.tips p {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
  font-weight: bold;
}

.tips ul {
  margin: 0;
  padding: 0;
}

.tips li {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
  text-align: center;
  list-style: none;
}
</style>
